#include "reg51.h"
#include "intrins.h"

#include "ds18b20.h"
#include "misc.h"
#include "iapEEPROM.h"
#include "oled.h"

// 低功耗蓝牙(蓝牙4.0)条件编译
//#define BLE_BLUETOOTH

//typedef bit BOOL;

sfr P0M1 = 0x93;
sfr P0M0 = 0x94;
sfr P1M1 = 0x91;
sfr P1M0 = 0x92;
sfr P2M1 = 0x95;
sfr P2M0 = 0x96;
sfr P3M1 = 0xb1;
sfr P3M0 = 0xb2;
sfr P4M1 = 0xb3;
sfr P4M0 = 0xb4;
sfr P5M1 = 0xC9;
sfr P5M0 = 0xCA;
sfr P6M1 = 0xCB;
sfr P6M0 = 0xCC;
sfr P7M1 = 0xE1;
sfr P7M0 = 0xE2;

//#define BAUD  0xF400                  // 1200bps @ 11.0592MHz
//#define BAUD  0xFA00                  // 2400bps @ 11.0592MHz
//#define BAUD  0xFD00                  // 4800bps @ 11.0592MHz
#define BAUD 0xFE80 // 9600bps @ 11.0592MHz
//#define BAUD  0xFF40                  //19200bps @ 11.0592MHz
//#define   BAUD  0xFFA0                  //38400bps @ 11.0592MHz

uchar TBUF, RBUF;
uchar TDAT, RDAT;
uchar TCNT, RCNT;
uchar TBIT, RBIT;
BOOL TING, RING;
BOOL TEND, REND;

sfr AUXR = 0x8E;
sbit RXB = P3 ^ 4; //define UART TX/RX port
sbit TXB = P3 ^ 5;

sbit P32 = P3 ^ 2;

uchar SendData(uchar);
void Send(uchar *);
void InitUart(void);
void uart_print(uint);

uchar t, r;
#define BUFFER_SIZE 16
uchar buf[BUFFER_SIZE + 1], buf_p = 0;
uchar mystrcmp(uchar *, uchar *);

void main()
{

    int temper, set_temper, count = 0;
    uchar c_x = 0, s_x = 32, c_d = 1, s_d = 1;
#ifdef BLE_BLUETOOTH
    uchar status_connect = 0, status_recOK = 0;
#endif
    P1M0 = 0x00;
    P1M1 = 0x00;
    P3M0 = 0x04;
    P3M1 = 0x00;

    TMOD = 0x00; //timer0 in 16-bit auto reload mode
    AUXR = 0x80; //timer0 working at 1T mode
    TL0 = BAUD;
    TH0 = BAUD >> 8; //initial timer0 and set reload value
    TR0 = 1;         //tiemr0 start running
    ET0 = 1;         //enable timer0 interrupt
    PT0 = 1;         //improve timer0 interrupt priority
    EA = 1;          //open global interrupt switch

    InitUart(); //初始化串口
    delayms(10);
    LCD_Init3(); //初始化显示屏
    LCD_Clean();

    set_temper = IapReadByte(IAP_ADDRESS);
    set_temper *= 10; //放大10倍，以适应temper的范围
    if (set_temper < 200 || set_temper > 500)
        set_temper = 300;

    while (1)
    {

        temper = DS18B20Disp();

        LCD_Print("CUR ", temper, c_x, 2);
        LCD_Print("SET ", set_temper, s_x, 5);
        c_x += c_d;
        if (c_x < 0 || c_x > 48)
            c_d = -c_d;
        s_x += s_d;
        if (s_x < 0 || s_x > 48)
            s_d = -s_d;

        if (temper < set_temper - 1)
            P32 = 1; //set switch power on
        if (temper > set_temper + 1)
            P32 = 0; //set switch power off
            //		P32 = ~P32;

            // Print "count,temper,set_temper,switch_status"
#ifdef BLE_BLUETOOTH
        if (status_connect)
        {
            if (!status_recOK)
            {
                Send("+OK\r\n");
            }
            else
            {
#endif
                uart_print(count++);
                SendData(',');
                uart_print(temper);
                SendData(',');
                uart_print(set_temper);
                SendData(',');
                SendData('0' + (uchar)P32);
                Send("\r\n");
                // use sprintf to string
//            sprintf(l_buf,"%d,%d,%d,%d\r\n",count++,temper,set_temper,P32?1:0);
//            Send(l_buf);
#ifdef BLE_BLUETOOTH
            }
#endif
            delayms(1000);
#ifdef BLE_BLUETOOTH
        }
#endif

        if (REND)
        {
            REND = 0;
            EA = 0;
#ifdef BLE_BLUETOOTH
            if (buf[0] == '+')
            {
                if (mystrcmp(buf, "+CONNECTED\r\n"))
                {
                    status_connect = 1;
                    status_recOK = 0;
                }
                else if (mystrcmp(buf, "+DISCONNECT\r\n"))
                {
                    status_connect = 0;
                    status_recOK = 0;
                    //                    delayms(500);
                }
                else if (status_connect && mystrcmp(buf, "+OK\r\n"))
                {
                    status_recOK = 1;
                }
            }
            else
#endif
                if (buf[0] == '=')
            { //串口缓冲区接收到的温度格式“-xx\r\n”
                int rec_temper = 0, i = 1;
                while (buf[i])
                {
                    if (buf[i] >= '0' && buf[i] <= '9')
                        rec_temper = rec_temper * 10 + buf[i] - '0';
                    i++;
                }
                if (rec_temper >= 20 && rec_temper <= 50)
                {
                    IapEraseSector(IAP_ADDRESS); //扇区擦除
                    IapProgramByte(IAP_ADDRESS, rec_temper);
                    set_temper = rec_temper * 10;
                }
            }
            EA = 1;
        }
        else
        {
            delayms(500);
        }
    }
}

// 串口输出整数
void uart_print(uint num)
{
    uchar str[10];
    int i = 0;
    do
    {
        str[i++] = num % 10 + '0';
    } while ((num /= 10) > 0);
    while (i--)
        SendData(str[i]);
}

//-----------------------------------------
//Timer interrupt routine for UART

void tm0() interrupt 1
{
    if (RING)
    {
        if (--RCNT == 0)
        {
            RCNT = 3; //reset send baudrate counter
            if (--RBIT == 0)
            {
                //                RBUF = RDAT;            //save the data to RBUF
                RING = 0; //stop receive
                buf[buf_p] = RDAT;
                if (RDAT == 0x0a)
                {
                    buf[++buf_p] = 0;
                    REND = 1; //set receive completed flag
                    buf_p = 0;
                }
                else if (buf_p < BUFFER_SIZE)
                {
                    buf_p++;
                }
            }
            else
            {
                RDAT >>= 1;
                if (RXB)
                    RDAT |= 0x80; //shift RX data to RX buffer
            }
        }
    }
    else if (!RXB)
    {
        RING = 1; //set start receive flag
        RCNT = 4; //initial receive baudrate counter
        RBIT = 9; //initial receive bit number (8 data bits + 1 stop bit)
    }

    if (--TCNT == 0)
    {
        TCNT = 3; //reset send baudrate counter
        if (TING) //judge whether sending
        {
            if (TBIT == 0)
            {
                TXB = 0;     //send start bit
                TDAT = TBUF; //load data from TBUF to TDAT
                TBIT = 9;    //initial send bit number (8 data bits + 1 stop bit)
            }
            else
            {
                TDAT >>= 1; //shift data to CY
                if (--TBIT == 0)
                {
                    TXB = 1;
                    TING = 0; //stop send
                    TEND = 1; //set send completed flag
                }
                else
                {
                    TXB = CY; //write CY to TX port
                }
            }
        }
    }
}

//-----------------------------------------
//initial UART module variable

void InitUart()
{
    TING = 0;
    RING = 0;
    TEND = 1;
    REND = 0;
    TCNT = 0;
    RCNT = 0;
}

//-----------------------------------------
//Send UART data
uchar SendData(uchar dat)
{
    while (!TEND)
        ;
    TEND = 0;
    TBUF = dat;
    TING = 1;
    //	TCNT = 3;

    //	delayms(1);

    return dat;
}
// Send string to UART
void Send(uchar *str)
{
    while (*str)
    {
        SendData(*str);
        str++;
    }
}

uchar mystrcmp(uchar *dst, uchar *src)
{
    while (*src)
    {
        if (*src++ != *dst++)
            return 0;
    }
    return 1;
}